package org.jeecg.modules.demo.mall.yxstoreproduct.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.api.UpmsHelloApi;
import org.jeecg.modules.demo.mall.dto.ProductNumDto;
import org.jeecg.modules.demo.mall.entity.YxLevelProductDiscount;
import org.jeecg.modules.demo.mall.entity.YxMerchantStore;
import org.jeecg.modules.demo.mall.entity.YxStoreCategory;
import org.jeecg.modules.demo.mall.entity.YxStoreProduct;
import org.jeecg.modules.demo.mall.vo.GoodsInfoVo;
import org.jeecg.modules.demo.mall.yxlevelproductdiscount.service.IYxLevelProductDiscountService;
import org.jeecg.modules.demo.mall.yxmerchantstore.service.IYxMerchantStoreService;
import org.jeecg.modules.demo.mall.yxstorecategory.service.IYxStoreCategoryService;
import org.jeecg.modules.demo.mall.yxstoreproduct.service.IYxStoreProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: yx_store_product
 * @Author: jeecg-boot
 * @Date: 2023-10-19
 * @Version: V1.0
 */
@Api(tags = "yx_store_product")
@RestController
@RequestMapping("/mall/yxstoreproduct/yxStoreProduct")
@Slf4j
public class YxStoreProductController extends JeecgController<YxStoreProduct, IYxStoreProductService> {
    @Autowired
    private IYxStoreProductService yxStoreProductService;
    @Autowired
    private IYxStoreCategoryService yxStoreCategoryService;

    @Autowired
    private IYxMerchantStoreService yxMerchantStoreService;
    @Autowired
    private IYxLevelProductDiscountService yxLevelProductDiscountService;

    private final UpmsHelloApi upmsHelloApi;

    public YxStoreProductController(UpmsHelloApi upmsHelloApi) {
        this.upmsHelloApi = upmsHelloApi;
    }

    /**
     * 分页列表查询
     *
     * @param yxStoreProduct
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "yx_store_product-分页列表查询")
    @ApiOperation(value = "yx_store_product-分页列表查询", notes = "yx_store_product-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<YxStoreProduct>> queryPageList(YxStoreProduct yxStoreProduct,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       String merId) {
        QueryWrapper<YxStoreProduct> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(merId)) {
            queryWrapper.like("dept_ids", merId);
        }
        if (StringUtils.isNotBlank(yxStoreProduct.getStoreName())) {
            queryWrapper.like("store_name", yxStoreProduct.getStoreName());
        }
        queryWrapper.orderByDesc("create_time");
        Page<YxStoreProduct> page = new Page<YxStoreProduct>(pageNo, pageSize);
        IPage<YxStoreProduct> pageList = yxStoreProductService.page(page, queryWrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return Result.ok(pageList);
        }

        pageList.getRecords().forEach(product -> {
            YxStoreCategory byId = yxStoreCategoryService.getById(Integer.valueOf(product.getCateId()));
            if (ObjectUtils.isNotEmpty(byId)) {
                product.setCateName(byId.getCateName());
            }

            //查询商户商品的价格库存
            QueryWrapper<YxMerchantStore> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(merId)) {
                wrapper.eq("store_id", product.getId());
                wrapper.eq("merchant_id", merId);
                YxMerchantStore yxMerchantStore = yxMerchantStoreService.getOne(wrapper);
                //判断当前商品是否分配给当前商家
                if (ObjectUtils.isNotEmpty(yxMerchantStore)) {
                    //赋值库存价格
                    product.setPrice(yxMerchantStore.getPrice());
                    product.setStocks(yxMerchantStore.getStock());
                    product.setStatus(yxMerchantStore.getStatus());
                    product.setStoreId(yxMerchantStore.getId());
                }
            }
        });
        return Result.OK(pageList);
    }

    @ApiOperation(value = "yx_store_product-列表查询", notes = "yx_store_product-列表查询")
    @GetMapping(value = "/queryList")
    public Result<?> queryList() {
        List<YxStoreProduct> yxStoreProducts = yxStoreProductService.list();
        return Result.OK(yxStoreProducts);
    }

    /**
     * 添加
     *
     * @param yxStoreProduct
     * @return
     */
    @AutoLog(value = "yx_store_product-添加")
    @ApiOperation(value = "yx_store_product-添加", notes = "yx_store_product-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody YxStoreProduct yxStoreProduct) {
        yxStoreProductService.save(yxStoreProduct);
//		goodsSkuService.saveSku(yxStoreProduct);

        List<String> stringList = new ArrayList<>();
        //判断是否选择了商家
        if (yxStoreProduct.getMerchantStore() != null) {
            yxStoreProduct.getMerchantStore().stream().forEach(yxMerchantStore -> {
                YxMerchantStore merchantStore = new YxMerchantStore();
                BeanUtils.copyProperties(yxMerchantStore, merchantStore);
                merchantStore.setMerchantId(yxMerchantStore.getId());
                merchantStore.setStoreId(yxStoreProduct.getId());
                merchantStore.setName(yxMerchantStore.getName());
                merchantStore.setPersonalNum(yxStoreProduct.getPersonalNum());
                yxMerchantStoreService.save(merchantStore);
                stringList.add(yxMerchantStore.getId());
            });
        }
        String collect = stringList.stream().collect(Collectors.joining(","));
        yxStoreProduct.setDeptIds(collect);
        yxStoreProductService.updateById(yxStoreProduct);
        return Result.ok("添加成功");
    }


    /**
     * 编辑
     *
     * @param yxStoreProduct
     * @return
     */
    @AutoLog(value = "yx_store_product-编辑")
    @ApiOperation(value = "yx_store_product-编辑", notes = "yx_store_product-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody YxStoreProduct yxStoreProduct) {

        List<String> stringList = new ArrayList<>();
        if (yxStoreProduct.getMerchantStore() != null) {
            yxStoreProduct.getMerchantStore().stream().forEach(yxMerchantStore -> {
                YxMerchantStore merchantStore = new YxMerchantStore();
                BeanUtils.copyProperties(yxMerchantStore, merchantStore);
                merchantStore.setMerchantId(yxMerchantStore.getId());
                merchantStore.setStoreId(yxStoreProduct.getId());
                merchantStore.setName(yxMerchantStore.getName());
                yxMerchantStoreService.updateById(merchantStore);
                stringList.add(yxMerchantStore.getId());
            });
        }
        String collect = stringList.stream().collect(Collectors.joining(","));
        yxStoreProduct.setDeptIds(collect);
        yxStoreProductService.updateById(yxStoreProduct);

        //判断是否有删除数据 有的话删除商品商家关联表中对应的数据
        if (ObjectUtils.isNotEmpty(yxStoreProduct.getDeletedIds())) {
            yxMerchantStoreService.updateIsDel(yxStoreProduct);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 根据商品id查详情
     */
    @GetMapping("/getGoodsInfoById")
    public Result<?> getGoodsById(@RequestParam("goodsId") Long goodsId) {
        YxStoreProduct product = yxStoreProductService.getById(goodsId);
        if (ObjectUtils.isEmpty(product)) {
            return Result.error(606, "没有找到该商品");
        }
        GoodsInfoVo infoVo = new GoodsInfoVo();
//        List<GoodsSku> goodsSkuList = goodsSkuService.getByGoodsId(goodsId);

//        infoVo.setGoodsSkuList(goodsSkuList);
        return Result.OK(infoVo);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "yx_store_product-通过id删除")
    @ApiOperation(value = "yx_store_product-通过id删除", notes = "yx_store_product-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) Integer id) {
        yxStoreProductService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "yx_store_product-批量删除")
    @ApiOperation(value = "yx_store_product-批量删除", notes = "yx_store_product-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.yxStoreProductService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "yx_store_product-通过id查询")
    @ApiOperation(value = "yx_store_product-通过id查询", notes = "yx_store_product-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<YxStoreProduct> queryById(@RequestParam(name = "id", required = true) Integer id) {
        YxStoreProduct yxStoreProduct = yxStoreProductService.getById(id);
        if (yxStoreProduct == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(yxStoreProduct);
    }


    /**
     * 通过姓名查询
     *
     * @param title
     * @return
     */
    @ApiOperation(value = "通过姓名查询", notes = "通过姓名查询")
    @GetMapping(value = "/queryTitle")
    public YxStoreProduct queryTitle(@RequestParam(name = "title", required = true) String title) {
        LambdaQueryWrapper<YxStoreProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(YxStoreProduct::getStoreName, title);
        YxStoreProduct yxStoreProduct = yxStoreProductService.getOne(queryWrapper);
        if (yxStoreProduct == null) {
            return null;
        }
        return yxStoreProduct;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param yxStoreProduct
     */
    @RequiresPermissions("yxstoreproduct:yx_store_product:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YxStoreProduct yxStoreProduct) {
        return super.exportXls(request, yxStoreProduct, YxStoreProduct.class, "yx_store_product");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("yxstoreproduct:yx_store_product:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YxStoreProduct.class);
    }

    /**
     * 商家进行跃动商品的上下架操作
     */
    @PostMapping(value = "/updateStatus")
    public Result<?> updateStatus(@RequestBody YxStoreProduct yxStoreProduct) {
        YxMerchantStore yxMerchantStore = new YxMerchantStore();
        yxMerchantStore.setId(yxStoreProduct.getStoreId());
        yxMerchantStore.setStatus(yxStoreProduct.getStatus());
        yxMerchantStoreService.updateById(yxMerchantStore);
        return Result.OK("修改上下架状态成功!");
    }

    /**
     * 订单库存修改
     */
    @PostMapping(value = "/updateNum")
    public void updateNum(@RequestBody ProductNumDto productNumDto) {
        yxStoreProductService.updateNum(productNumDto.getProductId(), productNumDto.getNum(), productNumDto.getProductType(),productNumDto.getOrderPayType(),productNumDto.getSkuId(),productNumDto.getMerStoreId());
    }

    /**
     * 订单库存修改
     */
    @PostMapping(value = "/checkNum")
    public Boolean checkNum(@RequestBody ProductNumDto productNumDto) {
       return yxStoreProductService.checkNum(productNumDto.getProductId(), productNumDto.getNum(), productNumDto.getProductType(),productNumDto.getOrderPayType(),productNumDto.getSkuId(),productNumDto.getMerStoreId());
    }
    @GetMapping(value = "/queryName")
    public YxStoreProduct queryName(@RequestParam Integer storeId) {
        YxStoreProduct service = yxStoreProductService.getById(storeId);
        return service;
    }



    @ApiOperation(value = "商家商品信息表-分页列表查询", notes = "商家商品信息表-分页列表查询")
    @GetMapping(value = "/listMer")
    public Result<IPage<YxMerchantStore>> queryPageList(YxMerchantStore yxMerchantStore,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<YxMerchantStore> queryWrapper = QueryGenerator.initQueryWrapper(yxMerchantStore, req.getParameterMap());
        queryWrapper.eq("merchant_id", yxMerchantStore.getMerId());
        //状态是上架的
        Page<YxMerchantStore> page = new Page<YxMerchantStore>(pageNo, pageSize);
        IPage<YxMerchantStore> pageList = yxMerchantStoreService.page(page, queryWrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())) {
            return Result.ok(pageList);
        }

        pageList.getRecords().forEach(product -> {
            YxStoreProduct byId = yxStoreProductService.getById(product.getStoreId());
            if (byId!=null){
                product.setStoreName(byId.getStoreName());
            }
            //赋值库存价格
            YxLevelProductDiscount yxLevelProductDiscount = yxLevelProductDiscountService.queryLevelPrice(0, yxMerchantStore.getLevelId(), Integer.valueOf(yxMerchantStore.getMerId()), Long.valueOf(product.getStoreId()));
            if (yxLevelProductDiscount != null) {
                product.setLevelPrice(product.getPrice().multiply(yxLevelProductDiscount.getDiscount().divide(BigDecimal.valueOf(10), BigDecimal.ROUND_CEILING)).setScale(2, 4));
            }

        });
        return Result.OK(pageList);
    }

}
